package com.offcn.page.controller;

import com.alibaba.fastjson.JSON;
import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.page.service.PageService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/page")
public class PageController {

    @Autowired
    private PageService pageService;

    @Value("${pagepath}")
    public String pagepath;

    @RequestMapping("/createHtml/{goodsId}")
    public Result createHtml(@PathVariable Long goodsId){
        pageService.createPageHtml(goodsId);
        return new Result(true, StatusCode.OK,"页面生成成功");
    }

    //获取json格式数据
    @GetMapping("/{goodsId}")
    public Result getPageInfo(@PathVariable("goodsId") Long goodsId){
        //判断本地文件是否存在？
        File file = new File(pagepath + goodsId + ".json");

        if(!file.exists()){

        Map<String, Object> map = pageService.buildModel(goodsId);
        Result result = new Result(true, StatusCode.OK, map, "读取成功");

        //转换成json字符串
        String jsonStr = JSON.toJSONString(result);

        //转存成文件
        try {

            pageService.save(pagepath+goodsId+".json",jsonStr);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,StatusCode.OK,"生成页面失败");
        }

        }else {
           //读取文件内容到json字符串
            try {
                String jsonStr = FileUtils.readFileToString(file);
                Result result = JSON.parseObject(jsonStr, Result.class);
                return result;
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(false,StatusCode.OK,"获取页面失败");
            }
        }
    }
}
